<?php
namespace app\index\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use think\facade\Validate;
use think\facade\View;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

class Upload extends BaseController
{
    /**
     * 上传excel文件并解析，导入数据库
     */
    public function uploadExcel()
    {
        if (Request::isPost()) {
            // 获取上传的文件
            $file = Request::file('file');

            if (!$file) {
                return json(['code' => 1, 'msg' => 'No file uploaded']);
            }

            /* 验证文件类型和大小
            $validate = [
                'size' => 10485760, // 10MB
                'ext' => 'xls,xlsx',
            ];
            $fileInfo = $file->validate($validate);
            if (!$fileInfo) {
                return json(['status' => 'fail', 'message' => $file->getError()]);
            }*/

            // thinkphp6验证文件类型和大小
            $validate = Validate::rule([
                'file' => 'file|fileExt:xls,xlsx|fileSize:10485760', // 10MB
            ]);
            $data = ['file' => $file];
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' => $validate->getError()]);
            }

            // 将文件保存到临时路径
            $savePath = $file->getPathname();

            try {
                // 解析Excel文件
                $spreadsheet = IOFactory::load($savePath);
                $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);

                // 开启数据库事务
                Db::startTrans();
                try {
                    // 批量插入数据到数据库
                    foreach ($sheetData as $index => $row) {
                        if ($index == 0) {
                            // 跳过第一行标题行
                            continue;
                        }

                        // 假设有三列需要插入到数据库
                        Db::name('excel')->insert([
                            'name' => $row['A'],
                            'age' => $row['B'],
                            'hobby' => $row['C'],
                        ]);
                    }

                    // 提交事务
                    Db::commit();
                    return json(['code' => 0, 'msg' => 'Data imported successfully']);
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return json(['code' => 1, 'msg' => 'Data import failed: ' . $e->getMessage()]);
                }
            } catch (\PhpOffice\PhpSpreadsheet\Reader\Exception $e) {
                return json(['code' => 1, 'message' => 'Error reading file: ' . $e->getMessage()]);
            }
        } else {
            return View::fetch();
        }
    }

    /**
     * 上传图片，检验文件类型
     * @return mixed
     */
    public function uploadPicture()
    {
        if (Request::isPost()) {
            $file = Request::file('file');
            if (!$file) {
                return json(['code' => 1, 'msg' => '没有上传文件']);
            }

            $ext = $this->getMimeType($file->getMime());
            if($ext == 'unknown'){
                return json(['code' => 1, 'msg' => '该文件类型不允许上传']);
            }

            $info = \think\facade\Filesystem::disk('public')->putFile('uploads', $file);
            //TODO 保存到数据库
            if ($info) {
                return json(['code' => 0, 'msg' => '文件上传成功', 'url' => $info]);
            } else {
                return json(['code' => 1, 'msg' => '文件上传失败']);
            }
        }else{
            return <<<EOF
            <form action="" method="post" enctype="multipart/form-data">
                <input type="file" name="file">
                <input type="submit" value="Upload">
            </form>
            EOF;
        }

    }

    protected function getMimeType($mimeType): string
    {
        switch($mimeType){
            case 'image/jpeg':
                return 'jpg';
            case 'image/png':
                return 'png';
            case 'image/gif':
                return 'gif';
            case 'image/bmp':
                return 'bmp';
            case 'image/tiff':
                return 'tiff';
            case 'image/webp':
                return 'webp';
            default:
                return 'unknown';
        }
    }
}
